<?php

namespace app\admin\controller\report;

use app\admin\model\basic\Assets;
use app\admin\model\basic\Goods;
use app\admin\model\basic\Staff;
use app\admin\model\basic\Stash;
use app\admin\model\basic\Unit;
use app\admin\model\business\StashGoodsDetail;
use app\common\controller\Backend;
use app\common\model\Category;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\response\Json;

/**
 * 库存状况管理
 *
 * @icon fa fa-circle-o
 */
class StashDetail extends Backend
{

    /**
     * StashDetail模型对象
     * @var \app\admin\model\report\StashDetail
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\report\StashDetail;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);

        $stash = Stash::column('name', 'id');
        $assets = Assets::column('name', 'id');
        $staff = Staff::column('name', 'id');
        $unit = Unit::column('name', 'id');

        foreach ($list->items() as &$item) {
            $item['unit_id'] = $unit[$item['unit_id']] ?? '-';
            $item['stash_id'] = $stash[$item['stash_id']] ?? '-';
            $item['staff_id'] = $staff[$item['staff_id']] ?? '-';
            $item['assets_id'] = $assets[$item['assets_id']] ?? '-';
        }

        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


    /**
     * Notes: 单据详情
     * User: AerYYY
     * Date: 2/5/24 3:48 PM
     * @param $ids
     * @return mixed
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function detail()
    {
        $order_no = input('order_no');
        if (empty($order_no)) {
            $this->error('参数错误');
        }
        $info = $this->model->where('order_no', $order_no)->find();
        if (empty($info)) {
            $this->error('信息不存在');
        }
        $info['unit_name'] = Unit::where('id', $info['unit_id'])->value('name');
        $info['staff_name'] = Staff::where('id', $info['staff_id'])->value('name');

        if ($info['status'] == \app\admin\model\report\Finance::STATUS_DBD) {
            $list = StashGoodsDetail::where('order_no', $info['order_no'])->where('be', 1)->select();
        } else {
            $list = StashGoodsDetail::where('order_no', $info['order_no'])->select();
        }

        $num = 0;
        foreach ($list as &$item) {
            $item['goods'] = Goods::where('id', $item['goods_id'])->find();
            $item['amount'] = bcmul($item['qty'], $item['price'], 2);
            $num += $item['qty'];
        }
        $info['sum_qyt'] = $num;

        $info['status_name'] = \app\admin\model\report\Finance::STATUS_ARR[$info['status']] ?? '-';

        switch ($info['status']) {
            case \app\admin\model\report\Finance::STATUS_SH:
                $info['unit_key'] = '收货单位';
                break;
            case \app\admin\model\report\Finance::STATUS_SHTH:
                $info['unit_key'] = '退货单位';
                break;
            case \app\admin\model\report\Finance::STATUS_LS:
                $info['unit_key'] = '收货单位';
                break;
            case \app\admin\model\report\Finance::STATUS_JH:
                $info['unit_key'] = '供货单位';
                break;
            case \app\admin\model\report\Finance::STATUS_JHTH:
                $info['unit_key'] = '收货单位';
                break;
            case \app\admin\model\report\Finance::STATUS_DBD:
                $info['stash'] = Stash::where('id', $info['stash_id'])->find();
                $info['stash_c'] = Stash::where('id', $info['stash_c_id'])->find();
                break;
            case \app\admin\model\report\Finance::STATUS_QTR:
            case \app\admin\model\report\Finance::STATUS_QTC:
                $info['unit_key'] = '往来单位';
                $info['stash'] = Stash::where('id', $info['stash_id'])->find();
                $info['category'] = Category::where('id', $info['category_id'])->find();
                break;
            default:
                $info['unit_key'] = '单位';
        }

        $info['cn_price'] = num_to_cn_capital(floatval($info['price']));
        $this->assign('info', $info);
        $this->assign('list', $list);
        return $this->fetch();
    }

    /**
     * Notes: 修改各种单据
     * User: AerYYY
     * Date: 5/11/24 9:28 AM
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws \think\Exception
     */
    public function detail_edit()
    {
        $order_no = input('order_no');
        if (empty($order_no)) {
            $this->error('错误的参数');
        }
        $order = \app\admin\model\business\StashDetail::where('order_no', $order_no)->find();
        if (empty($order)) {
            $this->error('订单异常');
        }

        if (request()->isPost()) {
            $params = $this->request->post();
            $params['admin_id'] = $this->auth->id;

            $stashDetailModel = new \app\admin\model\business\StashDetail();
            $stashDetailModel->startTrans();
            try {
                switch ($order['status']) {
                    case 100:  //销售单
                        if (!$stashDetailModel->editXs($params)) {
                            $this->error($stashDetailModel->getError());
                        }
                        break;
                    case 200: //销售退货单
                        if (!$stashDetailModel->editXsthd($params)) {
                            $this->error($stashDetailModel->getError());
                        }
                        break;
                    case 400: //进货单
                        if (!$stashDetailModel->editJhd($params)) {
                            $this->error($stashDetailModel->getError());
                        }
                        break;
                    case 500://进货退货单
                        if (!$stashDetailModel->editThd($params)) {
                            $this->error($stashDetailModel->getError());
                        }
                        break;
                    case 1300://调拨单
                        $this->error('调拨单请直接删除，重新调拨就行。');
                        if (!$stashDetailModel->editDbd($params)) {
                            return false;
                        }
                        break;
                    case 1400://其他入库单
                        if (!$stashDetailModel->editQtrkd($params)) {
                            $this->error($stashDetailModel->getError());
                        }
                        break;
                    case 1500://其他出库单
                        if (!$stashDetailModel->editQtckd($params)) {
                            $this->error($stashDetailModel->getError());
                        }
                        break;
                    default:
                        $this->error = '异常类型';
                        return false;
                }

                $stashDetailModel->commit();
            } catch (Exception $exception) {
                $stashDetailModel->rollback();
                $this->error($exception->getMessage());
            }
            $this->success();
        }

        $list = StashGoodsDetail::alias('d')->join('goods g', 'g.id = d.goods_id', 'left')
            ->where('d.order_no', $order_no)
            ->field('d.*,g.name,g.id,g.number')->select();
        $sum_qty = 0;
        foreach ($list as $item) {
            $sum_qty += $item['qty'];
        }

        $this->assign('sum_qty', $sum_qty);
        $this->assign('list', $list);
        $this->assign('count', count($list) + 1);
        $this->assign('row', $order);
        return $this->view->fetch();

    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {

            if (!$this->model->delLog($ids)) {  // 删除的时候处理库存逻辑
                Db::rollback();
                $this->error($this->model->getError());
            }

            foreach ($list as $item) {
                $count += $item->delete();
            }

            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

}
